package com.ifast.oupei.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.ifast.oupei.dao.CompanyDao;
import com.ifast.oupei.dao.LeagueDao;
import com.ifast.oupei.dao.MatchDao;
import com.ifast.oupei.dao.OddsDao;
import com.ifast.oupei.dao.TeamDao;
import com.ifast.oupei.domain.LeagueDO;
import com.ifast.oupei.domain.MatchDO;
import com.ifast.oupei.domain.OddsDO;
import com.ifast.oupei.domain.SynthesisDO;
import com.ifast.oupei.domain.TeamDO;
import com.ifast.oupei.service.MatchService;
import com.ifast.oupei.service.OddsService;
import com.ifast.oupei.service.SynthesisService;
import com.ifast.oupei.util.HTMLParserUtil;
import com.ifast.oupei.util.PDFParserUtil;
import com.ifast.oupei.vo.MatchVO;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.base.CoreServiceImpl;
import com.ifast.common.service.DictService;

/**
 * 
 * <pre>
 * 比赛信息表
 * </pre>
 * 
 * <small> 2018-04-23 12:22:35 | Aron</small>
 */
@Service
public class MatchServiceImpl extends CoreServiceImpl<MatchDao, MatchDO> implements MatchService {
	@Autowired
	LeagueDao leagueDao;
	@Autowired
	CompanyDao companyDao;
	@Autowired
	TeamDao teamDao;
	@Autowired
	MatchDao matchDao;
	@Autowired
	OddsDao oddsDao;
	@Autowired
	OddsService oddsService;
	@Autowired
	DictService dictService;
	@Autowired
	private SynthesisService synthesisService;

	/**
	 * cupMatchDetail:当有轮次时候为1,2,3 当无轮次的时候，为准半决赛等
	 * 
	 * @throws IOException
	 */
	public String save(String leagueName, String season, String cupMatchDetail) throws IOException {
		LeagueDO leagueDO = new LeagueDO();
		if (cupMatchDetail.length() > 2) {// 杯赛
			leagueDO = leagueDao.listAllTurn2(leagueName, season, cupMatchDetail).get(0);
		} else {
			leagueDO = leagueDao.listAllTurn(leagueName, season).get(0);
		}
		String round = cupMatchDetail;
		if (leagueDO.getCupMatchDetail() != null && !"".equals(leagueDO.getCupMatchDetail()))
			round = leagueDO.getCupMatchDetail();// 当是分组赛的时候,轮次就是分组赛
		// 构造网址
		String url = "http://league.aicai.com/league/scoreresult!ajaxscoreResult.htm?leagueId="
				+ leagueDO.getAicaiLeagueId() + "&season=" + leagueDO.getSeason() + "&round=" + round + "&matchType=0";
		int period = leagueDO.getPeriod().intValue();
		List<MatchVO> matchVOList = new ArrayList<MatchVO>();
		matchVOList = HTMLParserUtil.getMatchList(url, leagueName, season, cupMatchDetail, period);
		for (MatchVO matchVO : matchVOList) {
			// 数据库是否有数据，如果有跳出
			if (matchDao.selectByTicketsId(matchVO.getTicketsId()) != null)
				continue;
			// 比赛数据信息插入
			MatchDO matchDO = new MatchDO();
			Integer hostTeamId = matchVO.getHometeamId();
			Integer guestTeamId = matchVO.getGuestteamId();
			if (teamDao.selectList(new EntityWrapper<TeamDO>().where("team_id = {0}", hostTeamId)).isEmpty()) {
				// 如果数据库没有球队信息，在数据库中插入数据信息
				TeamDO teamDO = new TeamDO();
				teamDO.setTeamName(matchVO.getHomeTeam());
				teamDO.setTeamId(hostTeamId);
				teamDO.setDetail(leagueName);
				teamDao.insert(teamDO);
			}

			if (teamDao.selectList(new EntityWrapper<TeamDO>().where("team_id = {0}", guestTeamId)).isEmpty()) {
				// 如果数据库没有球队信息，在数据库中插入数据信息
				TeamDO teamDO = new TeamDO();
				teamDO.setTeamId(guestTeamId);
				teamDO.setTeamName(matchVO.getGuestTeam());
				teamDO.setDetail(leagueName);
				teamDao.insert(teamDO);
			}

			try {
				BeanUtils.copyProperties(matchDO, matchVO);
			} catch (Exception e) {
			}
			matchDO.setLeagueId(leagueDO.getId());// 设置联赛id
			matchDO.setHomeTeam(null);
			matchDO.setGuestTeam(null);
			matchDao.insert(matchDO);

			// 赔率数据信息插入
			List<OddsDO> oddsVOList = HTMLParserUtil.getOddsList(matchDO.getId(), matchDO.getTicketsId(),
					companyDao.getTeamIdArray());
			for (OddsDO oddsDO : oddsVOList) {
				oddsDao.insert(oddsDO);
			}
		}

		return "添加数据成功";
	}

	/**
	 * cupMatchCode:当为杯赛时候，其值为15801这样的特殊，当为联赛时候，为联赛轮次，1.2.3等
	 */
	// /*public String save(String leagueName, String season, String
	// cupMatchCode) {
	// LeagueDO leagueDO = new LeagueDO();
	// if (cupMatchCode.length() > 3) {// 杯赛
	// leagueDO = leagueDao.listAllTurn2(leagueName, season,
	// cupMatchCode).get(0);
	// } else {
	// leagueDO = leagueDao.listAllTurn(leagueName, season).get(0);
	// }
	// String url = null;
	// int period = leagueDO.getPeriod().intValue();
	// String cupMatchDetail = leagueDO.getCupMatchDetail();
	// if (period > 0) {// 当存在周期时候
	// if (leagueDO.getCupMatchCode().length() > 3) {// 杯赛
	// url = "http://m.win007.com/info/cupmatch/" + season + "/" +
	// leagueDO.getLeagueId() + "_0_"
	// + leagueDO.getCupMatchCode() + ".htm";
	// } else {// 联赛
	// url = "http://m.win007.com/info/fixture/" + season + "/" +
	// leagueDO.getLeagueId() + "_"
	// + leagueDO.getCupMatchCode() + "_0.htm";
	// }
	// } else {// 不存在周期时候
	// if (cupMatchCode.length() > 3) {// 杯赛
	// url = "http://m.win007.com/info/cupmatch/" + season + "/" +
	// leagueDO.getLeagueId() + "_0_"
	// + cupMatchCode + ".htm";
	// } else {// 联赛
	// url = "http://m.win007.com/info/fixture/" + season + "/" +
	// leagueDO.getLeagueId() + "_0_" + cupMatchCode
	// + ".htm";
	//
	// }
	// }
	// int index = 0;
	// List<MatchVO> matchVOList = new ArrayList<MatchVO>();
	// try {
	// matchVOList = HTMLParserUtil.getMatchList(url, leagueName, season,
	// cupMatchCode, period, cupMatchDetail);
	// } catch (Exception e) {
	// }
	// index = matchVOList.size() + 1;
	// int company = 0;// 公司标示，当company=0，选择球探，当company=1，选择360
	// for (MatchVO matchVO : matchVOList) {
	// // 数据库是否有数据，如果有跳出
	// if (matchDao.selectByTicketsId(matchVO.getTicketsId()) != null)
	// continue;
	// // 比赛数据信息插入
	// MatchDO matchDO = new MatchDO();
	// String hostTeam = matchVO.getHometeam();
	// String guestTeam = matchVO.getGuestteam();
	// if (teamDao.selectList(new EntityWrapper<TeamDO>().where("team_name =
	// {0}", hostTeam)).isEmpty()) {
	// // 如果数据库没有球队信息，在数据库中插入数据信息
	// TeamDO teamDO = new TeamDO();
	// teamDO.setTeamName(hostTeam);
	// teamDao.insert(teamDO);
	// }
	// matchDO.setHometeamId(
	// teamDao.selectList(new EntityWrapper<TeamDO>().where("team_name = {0}",
	// hostTeam)).get(0).getId());
	// if (teamDao.selectList(new EntityWrapper<TeamDO>().where("team_name =
	// {0}", guestTeam)).isEmpty()) {
	// // 如果数据库没有球队信息，在数据库中插入数据信息
	// TeamDO teamDO = new TeamDO();
	// teamDO.setTeamName(guestTeam);
	// teamDao.insert(teamDO);
	// }
	// matchDO.setGuestteamId(
	// teamDao.selectList(new EntityWrapper<TeamDO>().where("team_name = {0}",
	// guestTeam)).get(0).getId());
	// try {
	// BeanUtils.copyProperties(matchDO, matchVO);
	// } catch (Exception e) {
	// }
	// matchDO.setLeagueId(leagueDO.getId());
	// matchDao.insert(matchDO);
	//
	// // 赔率数据信息插入
	// List<CompanyDO> companyDOList = companyDao.selectList(new
	// EntityWrapper<CompanyDO>());
	// for (CompanyDO companyDO : companyDOList) {
	// index = index + 1;
	// OddsDO oddsDO = new OddsDO();
	// OddsVO oddsVO = new OddsVO();
	// if (company == 0) {
	// oddsVO = HTMLParserUtil.get007OddsList(matchDO.getTicketsId(),
	// companyDO.getCompanyId(), index,
	// season);
	// if (oddsVO.getOddsdate() == null) {
	// company = 1;// 所有数据从360获取
	// oddsVO = HTMLParserUtil.get360OddsList(matchDO.getTicketsId(),
	// companyDO.getCompanyId(), index,
	// season);// 本条数据从360获取
	// }
	// } else {
	// oddsVO = HTMLParserUtil.get360OddsList(matchDO.getTicketsId(),
	// companyDO.getCompanyId(), index,
	// season);// 本条数据从360获取
	// }
	//
	// oddsDO.setCompanyId(companyDO.getCompanyId());
	// try {
	// BeanUtils.copyProperties(oddsDO, oddsVO);
	// } catch (Exception e) {// 没有赔率信息
	// System.out.println(e.toString());
	// }
	// oddsDO.setMatchId(matchDO.getId());
	// if (oddsDO.getOddsdate() != null && !"".equals(oddsDO.getOddsdate()))
	// oddsDao.insert(oddsDO);// 没有数据就插入
	// }
	// }
	// return "添加数据成功";
	// }*/

	public Page<MatchDO> ListAllMatchInfo(Page<MatchDO> page) {
		page.setRecords(matchDao.ListAllMatchInfo(page));
		return page;
	}

	// 根据id获取比赛
	public MatchDO selectByMatchId(Integer id) {
		return matchDao.selectByMatchId(id);
	}

	@Override
	public Page<MatchDO> selectisNotAnalyseMatchList(Page<MatchDO> page) {
		page.setRecords(matchDao.selectisNotAnalyseMatchList(page));
		return page;
	}

	@Override
	public Page<MatchDO> selectErrorAnalyseMatchList(Page<MatchDO> page) {
		page.setRecords(matchDao.selectErrorAnalyseMatchList(page));
		return page;
	}

	@Override
	public Page<MatchDO> selectisQuestionMatchList(Page<MatchDO> page) {
		page.setRecords(matchDao.selectisQuestionMatchList(page));
		return page;
	}

	// 对elements进行清洗，对数据库已经存在的进行移除。
	@Override
	public Elements getElements(Elements eles) {
		for (Element element : eles) {
			Integer ticketsId = Integer
					.parseInt(element.attr("onclick").replace("ToAnaly(", "").replace(" ,-1)", "").replace(" ,0)", ""));// 联赛id
			MatchDO matchDO = matchDao.selectByTicketsId(ticketsId);
			System.out.println(matchDO);
			if (matchDO != null)
				eles.remove(element);
		}
		return eles;
	}

	// 获取所有的轮次
	@Override
	public String[] getTurnList(Integer leagueId) {
		return matchDao.getTurnList(leagueId);
	}

	// 获取默认轮次
	@Override
	public String getTurn(Integer leagueId) {
		return matchDao.getTurn(leagueId);
	}

	// 获取某轮次的比赛
	@Override
	public List<MatchVO> getMatchByIdAndTurn(Integer id, String turn) {
		return matchDao.getMatchByIdAndTurn(id, turn);
	}

	// 获取一场比赛的所有信息
	@Override
	public MatchVO getMatchInfo(Integer ticketsId) {
		return matchDao.getMatchInfo(ticketsId);
	}

	@Override
	// 获取历史比赛的所有信息
	public List<MatchVO> getHistoryMatchList(Integer hometeamId, Integer guestteamId, String date, Integer limit,
			Integer companyId, Integer id) {
		return matchDao.getHistoryMatchList(hometeamId, guestteamId, date, limit, companyId, id);
	}

	@Override
	// 获取近期limit场比赛的所有信息
	public List<MatchVO> getLateMatchList(Integer teamId, String date, Integer limit, Integer companyId, Integer id) {
		return matchDao.getLateMatchList(teamId, date, limit, companyId, id);
	}

	// 获取下载的document列表
	@Override
	public List<Document> getDocuments(List<MatchVO> matchList, boolean all) throws Exception {
		File directory = new File("");// 参数为空
		String fileTemplatePath = directory.getCanonicalPath() + "\\source\\";
		String template = "leagues";
		List<Document> docs = new ArrayList<Document>();
		if (all) {
			// 添加综合分析列表
			Map<String, Object> vars = new HashMap<String, Object>();
			vars.put("matchList", matchList);

			for (MatchVO matchVO : matchList) {
				String homepower = "";
				String guestpower = "";
				try {
					homepower = dictService.getName("team_power", matchVO.getHometeamPower().toString());
				} catch (Exception e) {
					homepower = "未分析";
				}
				try {
					guestpower = dictService.getName("team_power", matchVO.getGuestteamPower().toString());
				} catch (Exception e) {
					guestpower = "未分析";
				}
				matchVO.setHomepower(homepower);
				matchVO.setGuestpower(guestpower);
			}
			MatchVO match1 = matchList.get(0);
			SynthesisDO synthesisDO = synthesisService.selectOne(new EntityWrapper<SynthesisDO>()
					.where("league_id = {0}", match1.getLeagueId()).andNew("turn = {0}", match1.getTurn()));
			String content = "";
			try {
				content = synthesisDO.getContent();
			} catch (Exception e) {
				content = "未分析";
			}
			content = content.replace("<br>", "<br/>");
			if (content.contains("<img"))
				content = HTMLParserUtil.getImageCotent(content);
			vars.put("content", content);
			String title = match1.getLeagueName() + match1.getSeason() + "赛季第" + match1.getTurn() + "轮";
			vars.put("title", title);
			docs.add(PDFParserUtil.generate(fileTemplatePath, "overall", vars));// 获取document
		}
		// 添加每场比赛
		for (MatchVO match : matchList) {
			if( match.getAnalysecontent()!=null){
				String analysecontent = match.getAnalysecontent().replace("<br>", "<br/>");
				match.setAnalysecontent(analysecontent);
			}
			if( match.getReplaycontent()!=null){
				String replaycontent=match.getReplaycontent().replace("<br>", "<br/>");
				match.setReplaycontent(replaycontent);
			}
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("match", match);// 比赛信息放入参数中
			map.put("oddsList", oddsDao.getOddsList(match.getId()));
			String date = new SimpleDateFormat("YYYY-MM-dd").format(match.getMatchDate());
			List<MatchVO> historyMatchList = matchDao.getHistoryMatchList(match.getHometeamId(), match.getGuestteamId(),
					date, 6, 21, match.getId());// 历史战绩
			List<MatchVO> homeMatchList = matchDao.getLateMatchList(match.getHometeamId(), date, 7, 21, match.getId());// 主队近期战绩
			List<MatchVO> guestMatchList = matchDao.getLateMatchList(match.getGuestteamId(), date, 7, 21,
					match.getId());// 客队近期战绩
			if (historyMatchList.size() < 7) { // 当往绩小于6时候
				int a = 6 - historyMatchList.size();
				for (int i = 0; i < a; i++) {
					historyMatchList.add(new MatchVO());
				}
			}
			String power = "";
			try {
				power = dictService.getName("team_power", match.getHometeamPower().toString()) + "vs"
						+ dictService.getName("team_power", match.getGuestteamPower().toString());
			} catch (Exception e) {
				power = "未分析";
			}
			map.put("power", power);// 广义实力
			map.put("historyMatchList", historyMatchList);// 历史战绩信息放入参数中
			map.put("homeMatchList", homeMatchList);// 主队近期战绩信息放入参数中
			map.put("guestMatchList", guestMatchList);// 客队近期战绩信息放入参数中

			List<OddsDO> oddsList = oddsService.getOddsList(match.getId());// 赔率信息
			List<OddsDO> oddsList1 = new ArrayList<OddsDO>();
			List<OddsDO> oddsList2 = new ArrayList<OddsDO>();
			for (int j = 0; j < oddsList.size(); j++) {
				Integer companyId = oddsList.get(j).getCompanyId();
				if (companyId != 23 && companyId != 24 && companyId != 26) {
					oddsList2.add(oddsList.get(j));
				}else{
					oddsList1.add(oddsList.get(j));
				}
			}
			map.put("oddsList1", oddsList1);// 赔率1
			if(oddsList2.size()<4){
				for(int i =oddsList2.size();i<4;i++){
					oddsList2.add(new OddsDO());
				}
			}
			map.put("oddsDO1", oddsList2.get(0));// 赔率2
			map.put("oddsDO2", oddsList2.get(1));// 赔率2
			map.put("oddsDO3", oddsList2.get(2));// 赔率2
			map.put("oddsDO4", oddsList2.get(3));// 赔率2
			docs.add(PDFParserUtil.generate(fileTemplatePath, template, map));// 获取document
		}
		return docs;
	}

	// 获取没有比分的比赛列表
	@Override
	public List<MatchDO> getScoreList() {
		return matchDao.getScoreList();
	}

	@Override
	// 获取没有比分的比赛列表
	public List<MatchDO> getNoOddsList() {
		return matchDao.getNoOddsList();
	}
}
